package com.wang.gulimall.product.exception;

import com.wang.common.exception.BizCodeEnum;
import com.wang.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 *  @author 子凡
 *  集中处理所有的异常
 */
//@ControllerAdvice(basePackages = "com.wang.gulimall.product.controller")
//@ResponseBody
//返回一个Json字符串
@RestControllerAdvice(basePackages = "com.wang.gulimall.product.controller")
@Slf4j
public class GlobalExceptionControllerAdvice {

    /**
     *  接受异常的类型
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            errMap.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",errMap);
    }

//    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e){
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }
}
